﻿@model HotelRegistrationSystem.Models.BookingModel

@{
    ViewBag.Title = "RoomBooking";
}

@Styles.Render("~/Content/themes/start/css")

<h2>RoomBooking</h2>
<div class="row">

    <div class="six columns">
        @{        
            var pic = ViewBag.Picture;
            string picturePath = pic != null ?
            string.Format("/Pictures_Hotels/{0}", pic.PictureName) :
                "~/Content/images/prod_large.jpg";
        }
        <img src="@picturePath"
             onerror="this.src = '/Content/images/prod_large.jpg'"/>
    </div>

    <div class="six columns">
        <div class="panel">
            @if (!string.IsNullOrEmpty(ViewBag.Message))
            {
                if (ViewBag.IsErr != null && !(bool)ViewBag.IsErr)
				{
					<p class="success_msg">
						<text>@ViewBag.Message</text>
					</p>
				}
				else
				{
					<p class="error_msg">
						<text>@ViewBag.Message</text>
					</p>
				}
			}
            @using (Html.BeginForm("RoomBooking", "Hotel"))
			{
                <label>
                    <strong>Hotel name:</strong>
                </label>    
                @Html.DisplayFor(m => m.HotelName)
                <br />
                <br />
        
                <label>
                    <strong>Rooms:</strong>
                </label>
				@Html.DropDownListFor(m => m.SelectedRoomId, new SelectList(Model.Rooms, "Id", "SummaryName"),
					new { id = "ddl_room_id" })
				@Html.ValidationMessageFor(m => m.SelectedRoomId)
                <br />
                <br />
            
                <label>
                    <strong>Pick start date:</strong>
                </label>
                @Html.EditorFor(m => m.StartDate)
                @Html.ValidationMessageFor(m => m.StartDate) <br />
            
                <label>
                    <strong>Pick end date:</strong>
                </label>
                @Html.EditorFor(m => m.EndDate)
                @Html.ValidationMessageFor(m => m.EndDate) <br />

                @Html.HiddenFor(m => m.HotelId)
                @Html.HiddenFor(m => m.HotelName)
            
                <input id="btn_calc" class="button small success" type="button" value="Calculate price" onclick="calculate();" />
                <p id="total_price" style="display: none; font-size: 24px">
                    Total: <span id="grandTotal">$0</span>
                </p>
                <input id="submit_form" class="button small radius" type="submit" value="Book it!" style="display: none;" />
			}
        </div>
    </div>
</div>

@section scripts{
    @Scripts.Render("~/bundles/jqueryui")
    <script type="text/javascript">
        Date.daysBetween = function (date1_ms, date2_ms) {
            //Get 1 day in milliseconds
            var one_day = 1000 * 60 * 60 * 24;

            // Calculate the difference in milliseconds
            var difference_ms = date2_ms - date1_ms;

            // Convert back to days and return
            return Math.round(difference_ms / one_day);
        }

        function calculate() {
            // Hide total price and submit button
            $('#total_price').hide();
            $('#submit_form').hide();

            // Get prices
            var roomIds = [
            @foreach (var room in Model.Rooms)
			{
                @room.Id<text>,</text>
			}];
            var roomPrices = [
            @foreach (var room in Model.Rooms)
			{
               @room.Price.ToString().Replace(',','.')<text>,</text>
			}];

            // Get Dates
        	var datepickers = $('.date');
            var startDateMs = Date.parse(datepickers[0].value);
            var endDateMs = Date.parse(datepickers[1].value);

            console.log('start ' + datepickers[0].value);
            console.log('end ' + datepickers[1].value);

            if (endDateMs <= startDateMs) {
                alert('Booking end date must be after booking start date!')
                return;
            }

            // Get days between the two dates
            var totalDays = Date.daysBetween(startDateMs, endDateMs);

            // Get the price of room
            for (var i = 0; i < roomIds.length; i++) {
            	if (roomIds[i] == $('#ddl_room_id').val()) {

            		console.log('price ' + parseFloat(roomPrices[i]));
            		console.log('totalDays ' + totalDays);

            		var totalPrice = parseFloat(roomPrices[i]) * totalDays;
                    if (isNaN(totalPrice))
                        totalPrice = 0;
                    $('#grandTotal').text('$' + totalPrice);
                    $('#total_price').show();
                    $('#submit_form').show();
                }
            }
        }

        jQuery(function ($) {
            $(document).ready(function () {
                var month =@Model.StartDate.Month -1;
            	var date = new Date('@Model.StartDate.Year', month, '@Model.StartDate.Day', 0, 0, 0, 0);
                $('.date').datepicker({
                	dateFormat: "dd MM yy",
                    minDate: date,
                });
            });
        });
    </script>
}